import { Modal, Steps, Form, Row, message, Spin, Button } from 'antd';
import React, { useState, useCallback } from 'react';
import { useRequest } from '@umijs/hooks';
import Step1 from './Step1';
import Step2 from './Step2';
import { getUserDetail, updateUser } from '../../service';

const { confirm } = Modal;

const Add = function Add({
  visible,
  onClose,
  title = '新增用户',
  data = {},
  form,
  isEdit = false,
  onSuccess,
}) {
  const { validateFields } = form;
  const [step, setStep] = useState(0);
  const [checkedRoleKeys, setCheckedRoleKeys] = useState([]);
  const [preCheckedRoleKeys, setPreCheckedRoleKeys] = useState([]);
  const [preParams, setPreParams] = useState({});

  const { loading, run } = useRequest(updateUser, {
    manual: true,
    onSuccess() {
      message.success('保存成功!');
      onSuccess();
      onClose();
    },
  });

  const { data: currentUser = {}, loading: currentUserLoading } = useRequest(
    () => getUserDetail({ userId: data.id }),
    {
      refreshDeps: [data.id],
      onSuccess(res) {
        setPreParams({ ...res, ...preParams });
      },
    },
  );

  const onOk = useCallback(() => {
    if (step === 0) {
      validateFields(['userState', 'airportCode']).then(params => {
        run({ ...params, userId: currentUser.id });
      });
    } else {
      if (checkedRoleKeys.length > 0) {
        run({ ...preParams, roleIds: checkedRoleKeys, preRoleIds: preCheckedRoleKeys });
      } else {
        confirm({
          title: '提示',
          content: '还未为该用户选择任何角色权限，是否保存？',
          onOk() {
            run({ ...preParams, roleIds: checkedRoleKeys, preRoleIds: preCheckedRoleKeys });
          },
        });
      }
    }
  }, [validateFields, run, currentUser, step, checkedRoleKeys, preParams, preCheckedRoleKeys]);

  const onChangeStep = useCallback(
    current => {
      if (step > current) {
        setStep(current);
      }
    },
    [step],
  );

  const onNextStep = function onNextStep() {
    validateFields(['userState', 'airportCode']).then(params => {
      setPreParams({ ...preParams, ...params, userId: currentUser.id });
      setStep(1);
    });
  };

  const formLayout = {
    labelCol: { span: 9 },
    wrapperCol: { span: 15 },
  };

  const renderStep = function renderStep(currentStep, formInstance, initData) {
    if (currentStep === 0) {
      return <Step1 form={formInstance} data={initData} isEdit={isEdit} />;
    }
    return (
      <Step2
        form={formInstance}
        data={initData}
        checkedRoleKeys={checkedRoleKeys}
        setCheckedRoleKeys={setCheckedRoleKeys}
        setPreCheckedRoleKeys={setPreCheckedRoleKeys}
      />
    );
  };

  return (
    <Modal
      visible={visible}
      onCancel={onClose}
      title={title}
      width="72%"
      footer={[
        step === 1 && (
          <Button key="back" onClick={() => setStep(0)}>
            上一步
          </Button>
        ),
        <Button key="save" type="primary" loading={loading} onClick={onOk}>
          保存
        </Button>,
        step === 0 && (
          <Button key="next" onClick={onNextStep}>
            下一步
          </Button>
        ),
      ]}
      bodyStyle={{ minHeight: '50vh', display: 'flex', flexDirection: 'column' }}
    >
      <div style={{ width: '66%', margin: '0 auto' }}>
        <Steps
          labelPlacement="vertical"
          current={step}
          onChange={onChangeStep}
          style={{ marginBottom: 24 }}
        >
          <Steps.Step title="基本信息" />
          <Steps.Step title="分配角色" />
        </Steps>
      </div>
      <Row justify="center" type="flex" align="middle" style={{ flex: 1 }}>
        <Spin spinning={currentUserLoading} />
        <Form style={{ flex: 1 }} {...formLayout}>
          {renderStep(step, form, preParams)}
        </Form>
      </Row>
    </Modal>
  );
};

export default Form.create()(Add);
